package com.jwthhealth_pub.old.report.view;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.VideoView;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.LogUtil;
import com.jwthhealth_pub.common.base.BaseActivity;
import com.jwthhealth_pub.common.view.TitleLayout;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.report.model.resbody.SportSuggVideoResp;
import com.jwthhealth_pub.old.report.view.adapter.DetailDescAdapter;
import com.jwthhealth_pub.old.report.view.adapter.DetailPicAdapter;
import com.jwthhealth_pub.old.report.view.adapter.SportExplainAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

/**
 * 运动细节页面
 * Created by liuzhen on 2017/10/25.
 */

public class SportDetailExplActivity extends BaseActivity {

    @BindView(R.id.title_layout)
    TitleLayout titleLayout;
    @BindView(R.id.vv)
    VideoView vv;
    @BindView(R.id.rv_explain)
    RecyclerView rvExplain;
    @BindView(R.id.rv_detail_pic)
    RecyclerView rvDetailPic;
    @BindView(R.id.rv_detail_desc)
    RecyclerView rvDetailDesc;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_bottom_index)
    TextView tvBottomIndex;
    private SportSuggVideoResp.DataBean mData;
    private int mCurrentIndex = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //把标题栏和导航栏设置回黑色
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                Window window = getWindow();
//                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
////                window.setStatusBarColor(Color.BLACK);
//                window.setNavigationBarColor(Color.BLACK);
//            }
//        }

//        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_sport_detail_expl);
        ButterKnife.bind(this);


        String id = getIntent().getStringExtra("id");
        if (id != null) {
            getData(id);
        }

//        initVideo(_video_url);
//        initTextExplain(listBean.getMain_desc());
//        initDetailPic();
    }

    @Override
    protected void title() {

        titleLayout.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
                finish();
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {

            }

            @Override
            public void rightTextClick() {

            }
        });
    }

    private void getData(final String id) {
        Observable<SportSuggVideoResp.DataBean> observable = Observable.create(new ObservableOnSubscribe<SportSuggVideoResp.DataBean>() {
            @Override
            public void subscribe(ObservableEmitter<SportSuggVideoResp.DataBean> e) throws Exception {
                showLoadProgresbar();

                Call<SportSuggVideoResp> _call = ApiHelper.getSportSuggVideo(id);
                SportSuggVideoResp response = _call.execute().body();
                if (response != null) {
                    String code = response.getCode();
                    if (code != null) {
                        if (code.equals("0")) {
                            if (response.getData() != null)
                                e.onNext(response.getData());
                            else
                                e.onError(new Exception(getString(R.string.common_net_error)));
                        } else {
                            if (response.getMsg() != null)
                                e.onError(new Exception(response.getMsg()));
                            else
                                e.onError(new Exception(getString(R.string.common_net_error)));
                        }
                    } else {
                        e.onError(new Exception(getString(R.string.common_net_error)));
                    }
                } else {
                    e.onError(new Exception("response body is null"));
                }
            }
        });

        Observer<SportSuggVideoResp.DataBean> observer = new Observer<SportSuggVideoResp.DataBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(SportSuggVideoResp.DataBean o) {
                missLoadProgressbar();
                mData = o;
                if (o.getNow_id() != null && o.getNum() != null) {
                    renderingBottomIndex();
                    renderingUi(mData.getList().get(Integer.parseInt(o.getNum())));
                    if (mData == null) return;
                    if (mData.getName() != null)
                        titleLayout.setTitle(mData.getName());

                }
            }

            @Override
            public void onError(Throwable e) {
                missLoadProgressbar();
                LogUtil.toast(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        };

        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
    }

    /**
     * 更新底边导航
     */
    private void renderingBottomIndex() {

        if (mData == null) return;

        if (mCurrentIndex == -1) {
            if (mData.getNum() != null && mData.getNum().length()>0 && mData.getNow_id() != null) {
                mCurrentIndex = Integer.parseInt(mData.getNum());
                tvBottomIndex.setText((mCurrentIndex+1) + "/" + mData.getList().size());
            }
        } else {
            tvBottomIndex.setText((mCurrentIndex+1) + "/" + mData.getList().size());
        }


    }


    /**
     * rendering main data
     *
     * @param listBean data
     */
    private void renderingUi(SportSuggVideoResp.DataBean.ListBean listBean) {

        if (listBean == null) return;

        if (listBean.getVideo_name() != null){
            if (listBean.getVideo_name() != null)
                tvTitle.setText(listBean.getVideo_name());
        }

        if (listBean.getVideo_path() != null)
            initVideo(listBean.getVideo_path());

        if (listBean.getMain_desc() != null && listBean.getMain_desc().size() > 0)
            initTextExplain(listBean.getMain_desc());

        if (listBean.getThumb_list() != null && listBean.getThumb_list().size() > 0)
            initDetailPic(listBean.getThumb_list());

        if (listBean.getSport_desc() != null && listBean.getSport_desc().size() > 0)
            initDetailDesc(listBean.getSport_desc());

    }

    private void initDetailDesc(List<String> sport_desc) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvDetailDesc.setLayoutManager(layoutManager);
        rvDetailDesc.setAdapter(new DetailDescAdapter(this, sport_desc));
    }

    private void initDetailPic(List<String> thumb_list) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvDetailPic.setLayoutManager(layoutManager);
        rvDetailPic.setAdapter(new DetailPicAdapter(this, thumb_list));
    }

    //文字描述
    private void initTextExplain(List<SportSuggVideoResp.DataBean.ListBean.MainDescBean> main_desc) {
        rvExplain.setLayoutManager(new LinearLayoutManager(this));
        rvExplain.setAdapter(new SportExplainAdapter(this, main_desc));
    }


    //加载视频
    private void initVideo(String videoUrl) {
        vv.setVideoURI(Uri.parse(videoUrl));
        vv.start();
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.start();
                mp.setLooping(true);
            }
        });
    }

    @OnClick(R.id.btn_close)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vv.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (vv != null) {
            vv.start();
        }
    }

    @OnClick({R.id.btn_previous, R.id.btn_next, R.id.btn_previous_img, R.id.btn_next_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_previous:
            case R.id.btn_previous_img:
                gotoPrevious();
                break;
            case R.id.btn_next:
            case R.id.btn_next_img:
                gotoNext();
                break;
        }
    }

    //下一个动作
    private void gotoNext() {
        if (mCurrentIndex + 1 < mData.getList().size())
            mCurrentIndex++;

        renderingUi(mData.getList().get(mCurrentIndex));
        renderingBottomIndex();
    }

    //上一个动作
    private void gotoPrevious() {
        if (mCurrentIndex - 1 >= 0)
            mCurrentIndex--;

        renderingUi(mData.getList().get(mCurrentIndex));
        renderingBottomIndex();
    }
}
